package com.example.demo.service;

import com.example.demo.mapper.ScoreMapper;
import com.example.demo.mapper.Score_CopyMapper;
import com.example.demo.entity.Cluster;
import com.example.demo.entity.Point;
import com.example.demo.entity.Score_copy;
import com.example.demo.util.AprioriUtil;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class AprioriService {
    @Autowired
    private  ScoreMapper sm;
    @Autowired
    private Score_CopyMapper scm;

    private static final Map<String, List<String>> testMap = new HashMap<>();

    static {
        testMap.put("大学外语1", Lists.newArrayList("面向对象程序设计","高等数学"));
        testMap.put("高等数学", Lists.newArrayList("面向对象程序设计","大学外语1"));
    }
    /**
     *
     * @param clusters
     * @param term
     * dataList 存放所有学生的的科目
     * @return
     */
    public Map<String, Double> initData(Set<Cluster> clusters,String term){
        ArrayList<String> dataList=new ArrayList<>();
        String test="";
        for (Cluster cluster : clusters) {
            List<Point> members = cluster.getMembers();
            for(Point p:members){
                List<Score_copy> scoreByTermAndId = scm.findScoreByTermAndId(p.getId(), term);
                for(Score_copy s:scoreByTermAndId){
                    test+=s.getCourse()+";";
                }
                dataList.add(test);
                test="";
            }
        }
        System.out.println(dataList);
        Map<String, Integer> apriori = AprioriUtil.apriori(dataList);
        Map<String, Double> relationRules = AprioriUtil.getRelationRules(apriori);
        Set<String> rrKeySet = relationRules.keySet();
        AtomicInteger count = new AtomicInteger();
        for (String keyString : rrKeySet) {
            System.out.println(keyString + ":" + relationRules.get(keyString));
            String[] split = keyString.split("->");

            testMap.forEach((key, value) -> {
                if (split[0].contains(key)) {
                    value.forEach((keys -> {
                         if (split[1].contains(keys)) {
                             count.getAndIncrement();
                         }
                    }));
                }
            });
        }
        System.out.println("准确度："+ count.get() / (1.0 * rrKeySet.size()));
        return relationRules;
    }
}
